import * as Cesium from "cesium";
import Vue3Container from "./Vue3Container";
import { v4 } from "uuid";
/**
 * 自定义弹窗交互器
 */
export default class CesiumVue3Popover {
  constructor(parmas) {
    const {
      viewer, // cesium viewer
      slotComponent, // vue3 组件，插槽
      slotId, // 子节点id
      parentDomId, // 需要挂载的父节点 id
      cesiumEventType, // 需要注册cesium的事件
    } = parmas;
    this._handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
    this.viewer = viewer;
    this.instance = null; // 组件实例的控制实例
    this.pickPosition = null; // 当前点击的广告牌的世界坐标
    this._slotComponent = slotComponent; // vue3 组件，插槽
    this._slotId = slotId; // vue3 组件，插槽 id
    this._parentDomId = parentDomId; // 需要挂载的父节点 id
    this._cesiumEventType = cesiumEventType; // 需要注册cesium的事件
    this.init(); // 注册事件
    //
  }
  init() {
    this.instance = new Vue3Container({
      parentDomId: this._parentDomId,
      positionLeft: "0px",
      positionTop: "0px",
      slotId: this._slotId, // 子组件的DOM id  不要重复依赖这个找dom
      slotComponent: this._slotComponent, // 需要渲染的vue 组件
      slotData: null,
    });
    this.registerEvent(); // 绑定鼠标点击广告牌事件
  }
  // 绑定鼠标点击广告牌事件
  registerEvent() {
    const _this = this;
    const viewer = this.viewer;
    this._handler.setInputAction((event) => {
      const cartesian2 = event.position; // 鼠标点击的 平面位置
      const pick = viewer.scene.pick(cartesian2); // pick 是点击的物体
      if (Cesium.defined(pick)) {
        console.log("PICK 点击的物体信息", pick);
        _this.pickPosition = pick.id.position._value; // {广告牌的世界坐标}
        _this.instance.changePickData(pick);
        _this.instance.show();
      } else {
        _this.instance.hide();
      }
    }, this._cesiumEventType);

    viewer.scene.postRender.addEventListener(
      _this.domPositionChangeBySceneChange,
      _this
    );
    console.log("注册了事件");

    // viewer.scene.postRender.removeEventListener(
    //   _this.domPositionChangeBySceneChange,
    //   _this
    // );
  }
  // 实时获取 广告牌的世界坐标对应最新的 屏幕坐标并设置到dom上
  domPositionChangeBySceneChange() {
    if (this.instance && this.instance.status &&this.pickPosition && this.instance.dom ) {
      const scene = this.viewer.scene;
      console.log("实时监听视图变化");
      const winpos = scene.cartesianToCanvasCoordinates(this.pickPosition);
      if (winpos) {
        const dom = this.instance.dom;
        const left = winpos.x.toFixed(0) + "px";
        const top = winpos.y.toFixed(0) + "px";
        dom.style.left = left;
        dom.style.top = top;
      }
    }
  }
}
